<?php

namespace Respect\Environment;

use ArrayObject;

abstract class AbstractEnv extends ArrayObject implements EnvironmentableInterface
{

    protected $params = array();
    protected $paramParser;

    public function __construct(array $array = array(), $type = null)
    {
        parent::__construct($array, ArrayObject::ARRAY_AS_PROPS);
    }

    public function __invoke($varname)
    {
        return isset($this[$varname]) ? $this[$varname] : false;
    }

    public function getUriPath()
    {
        return '/' . trim(
            substr(
                $this->getRawUriPath(),
                strlen($this->getApplicationRoot())
            ),
            '/'
        );
    }

    public function getResourcePath()
    {
        $path = $this->getUriPath();
        $parts = explode('/', $path);
        $lastPart = array_pop($parts);
        $lastPart = explode('.', $lastPart);
        $lastPart = array_shift($lastPart);
        return implode('/', $parts) . '/' . $lastPart;
    }

    public function getUriExtension()
    {
        $path = $this->getRawUriPath();
        $pathParts = explode('/', $path);
        $extParts = array_pop($pathParts);
        $extParts = explode('.', $extParts);
        array_shift($extParts);
        return implode('.', $extParts);
    }

    public function getApplicationRoot()
    {
        $scriptFilenameParts = preg_split(
                '#[\\\/]#', //slashes for everyone
                $this['SCRIPT_FILENAME']
        );
        $requestPathParts = explode('/', $this->getRawUriPath());
        return '/' . trim(
            implode(
                '/',
                array_intersect($scriptFilenameParts, $requestPathParts)
            ),
            '/'
        );
    }

    public function getRawUriPath()
    {
        $uri = $this['REQUEST_URI'];
        $parts = explode('?', $uri);
        return array_shift($parts);
    }

}